package com.abc.handler;

import com.abc.utils.SparkRequestUtil;
import com.abc.dto.request.ApiRequestRequestDto;
import com.abc.dto.request.Message;
import com.abc.utils.SparkRequestWebSocketUtil;
import com.abc.utils.SpringBeanUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Collections;
import java.util.List;

public class ChatWebSocketHandler extends TextWebSocketHandler {

    private final SparkRequestWebSocketUtil sparkRequestWebSocketUtil;

    public ChatWebSocketHandler() {
        this.sparkRequestWebSocketUtil = SpringBeanUtil.getBean(SparkRequestWebSocketUtil.class);
    }

    @Override
    public void handleTextMessage(@NotNull WebSocketSession session, TextMessage message) {
        String input = message.getPayload();

        // 创建 ApiRequestRequestDto 对象
        ApiRequestRequestDto requestDto = new ApiRequestRequestDto();
        Message msg = new Message();
        msg.setContent(input);
        requestDto.setMessages(Collections.singletonList(msg));
        sparkRequestWebSocketUtil.sendApiStreamRequest(requestDto, session);
    }

    public void sendMessage(WebSocketSession session, String message) throws Exception {
        session.sendMessage(new TextMessage(message));
    }
}
